import { ref } from "vue";

export const useFeature = () => {
  let ListData = ref();
  let ListTotal = ref();
  let Entity = ref<any>();

  let Pagination = ref({ ListData, ListTotal });

  const LoadData = (store: any, param: any) => {
    return new Promise((resolve, reject) => {
      store
        .findPage(param)
        .then((res: any) => {
          ListData.value = res.data.content;
          ListTotal.value = res.data.totalElements;
          resolve(res.data);
        })
        .catch((e: any) => {
          reject(e);
        });
    });
  };

  const LoadList = (store: any, param: any) => {
    return new Promise((resolve, reject) => {
      store
        .findList(param)
        .then((res: any) => {
          resolve(res.data);
        })
        .catch((e: any) => {
          reject(e);
        });
    });
  };

  const LoadOne = (store: any, param: any) => {
    return new Promise((resolve, reject) => {
      store
        .findOne(param)
        .then((res: any) => {
          Entity.value = res.data;
          resolve(res.data);
        })
        .catch((e: any) => {
          reject(e);
        });
    });
  };

  const UpdateOne = (store: any, param: any) => {
    return new Promise((resolve, reject) => {
      let method = "update";
      if (!param.fdId) {
        method = "save";
      }
      store[method](param)
        .then((res: any) => {
          resolve(res);
        })
        .catch((e: any) => {
          reject(e);
        });
    });
  };

  const DeleteOne = (store: any, param: any) => {
    return new Promise((resolve, reject) => {
      store
        .deleteOne(param)
        .then((res: any) => {
          resolve(res);
        })
        .catch((e: any) => {
          reject(e);
        });
    });
  };

  return {
    Pagination,
    Entity,
    LoadData,
    LoadList,
    LoadOne,
    UpdateOne,
    DeleteOne,
  };
};
